package test;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Alipay {
	String tid = "XOR_1_000000000000000000000000000000_675C4653300B78057B03707C";
	String taobaoPwd = "3DES_2_000000000000000000000000000000_104AD6EDD6995D8D";

	CookieStore cs;
	public String getToken() {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		String _tb_token_Value = "";
		try {

			HttpGet httpget = new HttpGet("https://login.taobao.com/member/login.jhtml?style=alipay&goto=https%3A%2F%2Flab.alipay.com%2Fuser%2Fnavigate.htm");

			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			EntityUtils.consume(entity);

			System.out.println("Login form get: " + response.getStatusLine());
			System.out.println("Initial set of cookies:");
			List<Cookie> cookies = httpclient.getCookieStore().getCookies();
			if (cookies.isEmpty()) {
				System.out.println("None");
			} else {
				for (int i = 0; i < cookies.size(); i++) {
					System.out.println("- " + cookies.get(i).toString());
					if (cookies.get(i).getName().equals("_tb_token_")) {
						_tb_token_Value = cookies.get(i).getValue();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return _tb_token_Value;
	}

	public String login() {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		String _tb_token_Value = getToken();
		try {
			HttpPost httppost = new HttpPost("https://login.taobao.com/member/login.jhtml");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("_tb_token_", _tb_token_Value));
			nvps.add(new BasicNameValuePair("action", "Authenticator"));
			nvps.add(new BasicNameValuePair("callback", ""));
			nvps.add(new BasicNameValuePair("css_style", ""));
			nvps.add(new BasicNameValuePair("CtrlVersion", "1,0,0,7"));
			nvps.add(new BasicNameValuePair("event_submit_do_login", "anything"));
			nvps.add(new BasicNameValuePair("fc", "2"));
			nvps.add(new BasicNameValuePair("from", "alipay"));
			nvps.add(new BasicNameValuePair("from_encoding", ""));
			nvps.add(new BasicNameValuePair("full_redirect", ""));
			nvps.add(new BasicNameValuePair("guf", ""));
			nvps.add(new BasicNameValuePair("gvfdcname", "10"));
			nvps.add(new BasicNameValuePair("gvfdcre", ""));
			nvps.add(new BasicNameValuePair("isIgnore", ""));
			nvps.add(new BasicNameValuePair("llnick", ""));
			nvps.add(new BasicNameValuePair("loginType", "4"));
			nvps.add(new BasicNameValuePair("minipara", ""));
			nvps.add(new BasicNameValuePair("minititle", ""));
			nvps.add(new BasicNameValuePair("need_check_code", ""));
			nvps.add(new BasicNameValuePair("need_sign", ""));
			nvps.add(new BasicNameValuePair("need_user_id", ""));
			nvps.add(new BasicNameValuePair("not_duplite_str", ""));
			nvps.add(new BasicNameValuePair("popid", ""));
			nvps.add(new BasicNameValuePair("poy", ""));
			nvps.add(new BasicNameValuePair("pstrong", ""));
			nvps.add(new BasicNameValuePair("sign", ""));
			nvps.add(new BasicNameValuePair("style", "alipay"));
			nvps.add(new BasicNameValuePair("support", "000001"));
			nvps.add(new BasicNameValuePair("tid", tid));
			nvps.add(new BasicNameValuePair("TPL_checkcode", ""));
			nvps.add(new BasicNameValuePair("TPL_password", taobaoPwd));
			nvps.add(new BasicNameValuePair("TPL_redirect_url", "https://lab.alipay.com/consume/record/index.htm"));
			nvps.add(new BasicNameValuePair("TPL_username", "背靠背仰望"));

			httppost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			EntityUtils.consume(entity);

			System.out.println("Login form get: " + response.getStatusLine());
			System.out.println("Post logon cookies:");
			cs = httpclient.getCookieStore();
			List<Cookie> cookies = cs.getCookies();
			if (cookies.isEmpty()) {
				System.out.println("None");
			} else {
				for (int i = 0; i < cookies.size(); i++) {
					System.out.println("- " + cookies.get(i).toString());
				}
			}

			Header[] hs = response.getHeaders("Location");
			String location = "";
			for (int i = 0; i < hs.length; i++) {
				location = hs[i].getValue();
				System.out.println(location);
			}
			forward(location);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return _tb_token_Value;
	}

	public void forward(String location) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.setCookieStore(cs);
		try {
			HttpGet httpget = new HttpGet(location);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			EntityUtils.consume(entity);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	public void query(String _tb_token_Value) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.setCookieStore(cs);
		try {
			HttpPost httppost = new HttpPost("https://lab.alipay.com/consume/record/index.htm");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("_form_token", _tb_token_Value));
			nvps.add(new BasicNameValuePair("beginTime", "2011-01-01"));
			nvps.add(new BasicNameValuePair("bizSubType", ""));
			nvps.add(new BasicNameValuePair("consumePlace", "101"));
			nvps.add(new BasicNameValuePair("currentPageNo", "1"));
			nvps.add(new BasicNameValuePair("currentTab", "1"));
			nvps.add(new BasicNameValuePair("customerType", "2"));
			nvps.add(new BasicNameValuePair("endTime", "2011-10-02"));
			nvps.add(new BasicNameValuePair("inOut", ""));
			nvps.add(new BasicNameValuePair("keyword", "1_"));
			nvps.add(new BasicNameValuePair("orderBy", "1"));
			nvps.add(new BasicNameValuePair("payType", ""));
			nvps.add(new BasicNameValuePair("searchType", "1"));
			nvps.add(new BasicNameValuePair("timeType", "1"));
			httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			HttpResponse response = httpclient.execute(httppost);

			HttpEntity entity = response.getEntity();
			// EntityUtils.consume(entity);
			System.out.println("Login form get: " + response.getStatusLine());
//			System.out.println(EntityUtils.toString(response.getEntity()));
			
			  Document doc = Jsoup.parse(EntityUtils.toString(response.getEntity()));
		        Element ele = doc.getElementById("myScene");
		        if (ele != null) {
		            Elements eles = ele.getElementsByTag("span");
		            for (int i = 0; i < eles.size(); i++) {
		                ele = eles.get(i);
		                if ("page-link".equals(ele.attr("class"))) {
		                    String text = ele.text();
		                    System.out.println(text);
		                    text = text.substring(text.indexOf("共") + 1, text.lastIndexOf("条"));
		                }
		            }
		        }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		Alipay a = new Alipay();
		a.query(a.login());
		System.out.println(URLEncoder.encode("%C0%F6%C8%CB%C0%F6%D7%B1", "UTF-8") + "-------------");
//		System.out.println(URLDecoder.decode("%C0%F6%C8%CB%C0%F6%D7%B1", "UTF-8"));
	}
}
